package com.xckj.cycling.activity

import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.junca.android.base.CViewBinding
import com.lihang.chart.utils.ChartLineItem
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.config.SelectModeConfig
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.luck.picture.lib.language.LanguageConfig
import com.xckj.cycling.R
import com.xckj.cycling.databinding.ActivityEditRouteBinding
import com.xckj.cycling.dialog.DiscardRouteDialog
import com.xckj.cycling.framework.BaseActivityKt
import com.xckj.cycling.model.*
import com.xckj.cycling.utils.DensityUtil
import com.xckj.cycling.utils.GlideEngine
import com.xckj.cycling.utils.setCardBg
import com.yalantis.ucrop.util.ImageHeaderParser
import org.greenrobot.eventbus.EventBus
import java.io.File

/**
 * 编辑路线
 */
class EditRouteActivity : BaseActivityKt() {
    @CViewBinding
    lateinit var viewBinding: ActivityEditRouteBinding
    private val data: RouteLineModel? by lazy {
        intent.getParcelableExtra("data")
    }

    override fun initView(root: View, savedInstanceState: Bundle?) {
        super.initView(root, savedInstanceState)
        viewModel.navigationDetail.observe(this) {
            it?.detail?.apply {
                setData(this)
            }
        }
        val imageAdapter = ImageAdapter()
        viewBinding.imgsRv.adapter = imageAdapter

        data?.let {
            viewModel.loadNavigationDetail(it.cid ?: "")
            viewBinding.intro.setText(it.content)
            viewBinding.text.setText(it.name)
            imageAdapter.list.let { list ->
                it.fullimgs?.forEach {
                    list.add(LocalMedia().apply {
                        realPath = it
                    })
                }
                list.forEachIndexed { index, localMedia ->
                    localMedia.path = it.imgs?.get(index) ?: ""
                }
            }
            imageAdapter.notifyDataSetChanged()
        }
        viewBinding.name.setCardBg()
        viewBinding.clear.setOnClickListener {
            viewBinding.text.setText("")
        }
        setImagesCount(imageAdapter.list.size)
        viewBinding.bicycle.setCardBg()
        viewBinding.ground.setCardBg()
        viewBinding.imgs.setCardBg()
        viewBinding.introLl.setCardBg()

    }

    private fun setRecylcerView(
        recyclerView: RecyclerView,
        tv: TextView,
        bicycleAndGround: BicycleAndGround
    ) {
        tv.text = bicycleAndGround.txt
        recyclerView.adapter = BicycleAdapter().apply {
            bicycleAndGround.data?.let {
                this@EditRouteActivity.data?.let { _data ->
                    select = it.indexOfFirst {
                        _data.ground_text == bicycleAndGround.txt
                    }
                }
                setNewInstance(it.toMutableList())
            }
        }
    }

    private fun setData(detail: NavigationDetailModel) {
//        detail.bicycleType?.let {
//            setRecylcerView(viewBinding.bicycleRv, viewBinding.tvBicycle, it)
//        }
        detail.ground?.let {
            setRecylcerView(viewBinding.groundRv, viewBinding.tvGround, it)
        }
        viewBinding.title.tvTitle.text = getString(R.string.ride_details)
        Glide.with(this).load(detail.fulllineimg).into(viewBinding.map)
        val chartA = viewBinding.highlyChart.attChar
        detail.highly?.let {
            chartA.setHoriItems(it.x?.map {
                it.toString()
            }?.let { it1 -> ArrayList(it1) })
            chartA.setItems(
                arrayListOf(
                    ChartLineItem(
                        ArrayList(it.data),
                        R.color.teal_200,
                        "",
                        false,
                        false
                    )
                )
            )
            viewBinding.highlyChart.tvAtt.text =
                getString(R.string.leiji_pasheng, it.climb?.replace("feet", ""))
        }
        detail.overall?.let {
            viewBinding.info.distance.text = it.mileage
            viewBinding.info.totalKaluli.text = it.calories
            viewBinding.info.time.text = detail.timelength
            viewBinding.info.totalAtt.text = it.cumulativeRise
        }
        viewBinding.confirm.setOnClickListener {
            val text = viewBinding.text.text.toString()
            if (TextUtils.isEmpty(text)) {
                showMessage(getString(R.string.route_map_name_tips))
                return@setOnClickListener
            }
            showLoading()
            val model = AddRouteRequestModel(text)
            val d = data
//            val ground_text =
//                (viewBinding.groundRv.adapter as? BicycleAdapter)?.getType()?.name ?: ""
            model.ground =
                (viewBinding.groundRv.adapter as? BicycleAdapter)?.getType()?.id ?: 0
//            model.bicycleType =
//                (viewBinding.bicycleRv.adapter as? BicycleAdapter)?.getType()?.id ?: 0
            val a = viewBinding.imgsRv.adapter as? ImageAdapter
            model.imgs = a?.list?.map {
                "http" + it.realPath
            } ?: ArrayList()
            model.introduce = viewBinding.intro.text.toString()
            model.share = if (viewBinding.switchShare.isChecked) 1 else 2
            model.linestatus = if (viewBinding.switchPrivate.isChecked) 1 else 2
            viewModel.addRouteToPrivate(d, model) {
                if (d != null) {
                    d.name = model.name
                    d.ground_text = d.ground_text
                    d.content = model.introduce
                    EventBus.getDefault().post(d)
                }
                if (it.isSuccessful) {
                    showMessage(getString(R.string.add_success))
                } else {
                    showMessage(it.msg)
                }
                hideDialog()
                MainActivity.toMain(
                    this,
                    1,
                    shareFacebook = if (viewBinding.switchShare.isChecked) viewBinding.text.text.toString()
                        .let {
                            val content = viewBinding.intro.text.toString()
                            if (!TextUtils.isEmpty(content)) {
                                StringBuilder(it).append("\n").append(content).toString()
                            } else {
                                it
                            }
                        } else null, shareUrl = it.data?.let {
                        val result = ArrayList<String>()
                        result.add(detail.fulllineimg ?: "")
                        result.addAll(it)
                        result
                    })
            }
        }

    }

    override fun finish() {
        DiscardRouteDialog(this) {
            if (it) {
                super.finish()
            }
        }.show()
    }

    class BicycleAdapter :
        BaseQuickAdapter<Type, BaseViewHolder>(R.layout.list_item_bicycle_and_ground) {
        var select = 0
        override fun convert(holder: BaseViewHolder, item: Type) {
            val tv = holder.getView<TextView>(R.id.name)
            tv.text = item.name
            holder.itemView.isSelected = select == holder.absoluteAdapterPosition
            holder.itemView.setOnClickListener {
                select = holder.absoluteAdapterPosition
                notifyDataSetChanged()
            }
        }

        fun getType(): Type {
            return data[if (select < 0) 0 else select]
        }
    }

    private fun setImagesCount(count: Int) {
        viewBinding.tvImg.text = getString(R.string.images, count.toString(), 10)
    }

    inner class ImageAdapter :
        RecyclerView.Adapter<BaseViewHolder>() {

        val list = ArrayList<LocalMedia>()

        override fun getItemViewType(position: Int): Int {
            val size = list.size
            if (size == 10) {
                return 1
            }
            if (position < size) {
                return 1
            }
            return 0
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
            return BaseViewHolder(
                LayoutInflater.from(this@EditRouteActivity)
                    .inflate(R.layout.list_item_edit_imgs, parent, false)
            )
        }

        override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
            val img = holder.getView<ImageView>(R.id.img)

            if (holder.itemViewType == 1) {
                val item = list.get(holder.absoluteAdapterPosition)
                Glide.with(img).load(item.realPath)
                    .transform(
                        CenterCrop(),
                        RoundedCorners(DensityUtil.dip2px(this@EditRouteActivity, 6f))
                    )
                    .into(img)
                holder.getView<ImageView>(R.id.delete).let {
                    it.visibility = View.VISIBLE
                    it.setOnClickListener {
                        list.removeAt(holder.absoluteAdapterPosition)
                        setImagesCount(list.size)
                        notifyDataSetChanged()
                    }
                }
            } else {
                img.setImageResource(R.mipmap.ic_add)
                holder.itemView.setOnClickListener {
                    PictureSelector.create(this@EditRouteActivity)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
                        .setLanguage(LanguageConfig.ENGLISH)
                        .setMaxSelectNum(10 - list.size)
                        .setSelectionMode(SelectModeConfig.SINGLE)
                        .forResult(object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: java.util.ArrayList<LocalMedia>?) {
                                result?.let {

                                    uploadImage(getFileList(it)[0], it)
                                }
                            }

                            override fun onCancel() {

                            }

                        })
                }
            }

        }

        override fun getItemCount(): Int {
            val size = list.size
            if (size == 10) {
                return 10
            }
            return size + 1
        }

        private fun uploadImage(file: File, callback: ArrayList<LocalMedia>) {
            showLoading()
            loginViewModel.uploadImage(file) {
                hideDialog()

//                EventBus.getDefault().post(EventUploadAvatar)
                if (it.isSuccessful) {
                    callback[0].realPath = it.data?.fullurl
                    list.add(callback[0])
                    notifyDataSetChanged()

                    if (list.size == 10) {
                        viewBinding.imgsRv.scrollToPosition(list.size - 1)
                    } else {
                        viewBinding.imgsRv.scrollToPosition(list.size)
                    }
                    setImagesCount(list.size)
                } else {
                    showMessage(it.msg)
                }
            }
        }

        private fun getFileList(fileList: List<LocalMedia>): List<File> {
            var files = mutableListOf<File>()
            for (file in fileList) {
                var compressPath: String = if (file.isCompressed) {
                    file.compressPath
                } else {
                    if (file.realPath != null) {
                        file.realPath
                    } else {
                        file.path
                    }
                }
                files.add(File(compressPath))
            }
            return files
        }

    }
}